package com.powernode.Task;

import com.powernode.constant.Constants;
import com.powernode.entity.Goods;
import com.powernode.service.GoodsService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
@EnableScheduling
@Component
public class GoodsTask {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private GoodsService goodsService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Scheduled(cron = "0/3 * * * * *")
    public void initGoodsCache() {
        List<Goods> list = goodsService.list();
        list.forEach(goods -> {
            // 商品信息
            redisTemplate.opsForValue().set(Constants.REDIS_GOODS + goods.getId(), goods);
            // 商品库存
            //若redis中没有库存信息，则设置库存信息
            stringRedisTemplate.opsForValue().setIfAbsent(Constants.REDIS_STORE + goods.getId(), goods.getStore().toString());
        });
    }
}
